use ggez::{Context, GameResult};
use ggez::graphics;
use ggez::event::EventHandler;
use ggez::input::keyboard::KeyCode;
use ggez::input::keyboard::KeyMods;
use crate::map::Map;
use crate::tank::{Tank, TankState};
use crate::projectile::Projectile;
use crate::ai::{ SimpleAI};

pub struct Game {
    map: Map,
    tanks: Vec<Tank>,
    projectiles: Vec<Projectile>,
    font: graphics::Text,
}

impl Game {
    pub fn new(ctx: &mut Context) -> GameResult<Self> {
        let font = graphics::Text::default();
        
        // 创建地图
        let map = Map::new(20, 20);
        
        // 创建坦克
        let mut tanks = Vec::new();
        
        // 添加玩家坦克
        let player_tank = Tank::new(
            100.0,  // 生命值
            2.0,    // 移动速度
            5.0,    // 攻击范围
            25.0,   // 攻击伤害
            1.0,    // 攻击冷却
            graphics::Color::new(0.0, 1.0, 0.0, 1.0), // 绿色
            1.0, 1.0 // 起始位置
        );
        tanks.push(player_tank);
        
        // 添加AI坦克
        for i in 0..3 {
            let ai_tank = Tank::new(
                100.0,  // 生命值
                1.5,    // 移动速度
                5.0,    // 攻击范围
                20.0,   // 攻击伤害
                1.5,    // 攻击冷却
                graphics::Color::new(1.0, 0.0, 0.0, 1.0), // 红色
                15.0 + (i as f32 * 2.0), 5.0 // 起始位置
            );
            tanks.push(ai_tank);
        }
        
        let projectiles = Vec::new();
        
        Ok(Game {
            map,
            tanks,
            projectiles,
            font,
        })
    }
}

impl EventHandler for Game {
    fn update(&mut self, ctx: &mut Context) -> GameResult {
        // 更新所有坦克
        for i in 0..self.tanks.len() {
            if i > 0 { // AI坦克
                let perception = self.tanks[i].perceive(&self.tanks, &self.map);
                let action = SimpleAI::decide(&perception);
                self.tanks[i].execute_action(action, &mut self.projectiles);
            }
            
            // 更新坦克状态
            self.tanks[i].update();
        }
        
        // 更新所有炮弹
        self.projectiles.retain_mut(|projectile| {
            projectile.update();
            // 检查碰撞
            for tank in &mut self.tanks {
                if projectile.check_collision(tank) {
                    tank.take_damage(projectile.damage);
                    return false;
                }
            }
            // 检查地图碰撞
            !self.map.check_collision(projectile.position)
        });
        
        // 移除死亡坦克
        self.tanks.retain(|tank| tank.state != TankState::Destroyed);
        
        Ok(())
    }
    
    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        let mut canvas = graphics::Canvas::from_frame(ctx, graphics::Color::from([0.1, 0.2, 0.3, 1.0]));
        
        // 绘制地图
        self.map.draw(&mut canvas, ctx)?;
        
        // 绘制坦克
        for tank in &self.tanks {
            tank.draw(&mut canvas, ctx)?;
        }
        
        // 绘制炮弹
        for projectile in &self.projectiles {
            projectile.draw(&mut canvas, ctx)?;
        }
        
        // 绘制UI
        let fps = ggez::timer::fps(ctx);
        let fps_display = graphics::Text::new(format!("FPS: {:.1}", fps));
        canvas.draw(&fps_display, graphics::DrawParam::new().dest([10.0, 10.0]));
        
        canvas.finish(ctx)?;
        Ok(())
    }

    // fn key_down_event(&mut self, _ctx: &mut Context, keycode: KeyCode, _keymods: KeyMods) -> GameResult {
    //     match keycode {
    //         // 控制玩家坦克移动
    //         KeyCode::Up => {
    //             if let Some(player_tank) = self.tanks.get_mut(0) {
    //                 player_tank.move_up();
    //             }
    //         }
    //         KeyCode::Down => {
    //             if let Some(player_tank) = self.tanks.get_mut(0) {
    //                 player_tank.move_down();
    //             }
    //         }
    //         KeyCode::Left => {
    //             if let Some(player_tank) = self.tanks.get_mut(0) {
    //                 player_tank.move_left();
    //             }
    //         }
    //         KeyCode::Right => {
    //             if let Some(player_tank) = self.tanks.get_mut(0) {
    //                 player_tank.move_right();
    //             }
    //         }
    //         KeyCode::Space => {
    //             if let Some(player_tank) = self.tanks.get_mut(0) {
    //                 player_tank.attack(&mut self.projectiles);
    //             }
    //         }
    //    KeyCode::Escape => {
    //         _ctx.continuing = false;
    //    }
    //
    //         _ => {}
    //     }
    //     Ok(())
    // }
}